const express = require("express");
const { contact } = require("./db");
const dbContext = contact;

const router = express.Router();

// 获取所有
router.get("/", (req, res) => {
  if (!req.user.id)
    return res.status(500).json({
      message: "发生异常：[用户状态失效]",
    });
  dbContext.contactGetList((err, data) => {
    if (!err) {
      return res.status(200).json({
        message: "查询成功",
        data,
      });
    } else {
      return res.status(500).json({
        message: "发生异常：[" + err + "]",
      });
    }
  });
});

// 获取单个
router.get("/getcontact", (req, res) => {
  dbContext.contactGetSingle(req.body.id, (err, data) => {
    if (!err) {
      return res.status(200).json({
        message: "查询成功",
        data,
      });
    } else {
      return res.status(500).json({
        message: "发生异常：[" + err + "]",
      });
    }
  });
});

// 新增联系方式
router.post("/addcontact", (req, res) => {
  const {
    companyname,
    companytel,
    companyphone,
    companyemail,
    companyaddress,
    companymap,
  } = req.body;
  dbContext.contactAdd(
    companyname,
    companytel,
    companyphone,
    companyemail,
    companyaddress,
    companymap,
    (err) => {
      if (!err) {
        return res.status(200).json({
          message: "添加成功",
        });
      } else {
        return res.status(500).json({
          message: "发生异常：[" + err + "]",
        });
      }
    }
  );
});

//修改联系方式
router.put("/updatecontact", (req, res) => {
  const {
    id,
    companyname,
    companytel,
    companyphone,
    companyemail,
    companyaddress,
    companymap,
  } = req.body;
  dbContext.contactUpdate(
    companyname,
    companytel,
    companyphone,
    companyemail,
    companyaddress,
    companymap,
    id,
    (err) => {
      if (!err) {
        return res.status(200).json({
          message: "修改成功",
        });
      } else {
        return res.status(500).json({
          message: "发生异常：[" + err + "]",
        });
      }
    }
  );
});

// 删除联系方式
router.delete("/delcontact", (req, res) => {
  dbContext.contactDel(req.body.id, (err) => {
    if (!err) {
      return res.status(200).json({
        message: "删除成功",
      });
    } else {
      return res.status(500).json({
        message: "发生异常：[" + err + "]",
      });
    }
  });
});

module.exports = router;
